﻿using System;
using System.IO;
using System.Text.RegularExpressions;

namespace GoodStuff.Text
{
    /// <summary>
    /// Utility class to read Comma Separated Value files.
    /// </summary>
    public class CSVStreamReader
    {
        private string _separator;
        private TextReader _reader;
        private string[] _columns;
        private int _row;

        /// <summary>
        /// Construct a new CSV reader with a specified separator
        /// </summary>
        /// <param name="reader">The TextReader to read contents from</param>
        /// <param name="separator">The separator used in that file</param>
        public CSVStreamReader(TextReader reader, string separator)
        {
            _reader = reader;
            _separator = separator;
            _row = 0;
            MoveNext();
        }

        /// <summary>
        /// Returns the current row number, starting with Row 1 for any valid file
        /// </summary>
        public int Row
        {
            get
            {
                return _row;
            }
        }

        /// <summary>
        /// Gets a value that signifies the end of the stream.
        /// </summary>
        public bool EndOfFile
        {
            get
            {
                return _columns == null;
            }
        }

        /// <summary>
        /// Gets the number of columns in the current row.
        /// </summary>
        public int Columns
        {
            get
            {
                return _columns.Length;
            }
        }

        /// <summary>
        /// Returns the value of a numbered column as a string value
        /// </summary>
        /// <param name="index">the column number to return the value for. Stars at 0</param>
        /// <returns></returns>
        public string this[int index]
        {
            get
            {
                return _columns[index];
            }
        }

        /// <summary>
        /// Moves the reader to the next row.
        /// </summary>
        /// <remarks>Will throw an exception if you try to read past EndOfFile</remarks>
        public void MoveNext()
        {
            string line = _reader.ReadLine();
            if (line != null)
            {
                _row++;
                CSVStringSplitter splitter = new CSVStringSplitter(_separator);
                _columns = splitter.Split(line);
            }
            else
            {
                _columns = null;
            }    
        }
    }
}
